<template>
  <div class="app-container">
    <el-col :xs="24">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                  :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px"/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
      <el-card shadow="hover">
        <template #header>
          <el-row justify="space-between" style="margin-bottom: 0;">
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button type="primary" plain @click="handleAdd()" icon="Plus">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button plain @click="handleAdd()">
                  <svg-icon icon-class="export"/>
                  <span style="color: rgb(0, 112, 255);">导出</span>
                </el-button>
              </el-col>
            </el-row>
            <div class="rightToolbar">
              <el-radio-group v-model="layoutType">
                <el-radio-button label="table">
                  <svg-icon icon-class="table2"/>
                </el-radio-button>
                <el-radio-button label="card">
                  <svg-icon icon-class="card"/>
                </el-radio-button>
              </el-radio-group>
            </div>
          </el-row>
        </template>

        <!-- 表格-->
        <template v-if="layoutType=='table'">
          <el-table v-loading="loading" :data="productList">
            <el-table-column label="产品Key" align="center" key="productKey" prop="productKey"/>
            <el-table-column label="产品名称" align="center" key="name" prop="name"/>
            <el-table-column label="品类" align="center" key="categoryId" prop="categoryId"/>
            <el-table-column label="传输协议" align="center" key="transMode" prop="transMode">
              <template #default="scope">
                <span>{{ computedTransMode(scope.row.transMode) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="设备定位" align="center" key="openLocate" prop="openLocate">
              <template #default="scope">
                <span>{{ computedOpenLocate(scope.row.openLocate, scope.row.locateUpdateType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="产品图片" align="center" key="img" prop="img">
              <template #default="scope">
                <img :src="scope.row.imgUrl || defaultImg" alt="" style="height: 50px;width: 50px">
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" key="createTime" prop="createTime"/>
            <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="详情" placement="top">
                  <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
                </el-tooltip>
                <el-divider direction="vertical"/>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-divider direction="vertical"/>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
                <el-divider direction="vertical"/>
                <el-tooltip content="物模型" placement="top">
                  <el-button link type="primary" icon="ScaleToOriginal" @click="openObjectModel(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <template v-else>
          <el-row class="card-list " style="display: flex">
            <el-col class="card-item" v-for="(item,index) in productList" :key="index">
              <div class="text-box">
                <div class="title align-center" style="display: flex">
                  <div class="icon">
                    <svg-icon icon-class="cube" class="design-iconfont"/>
                  </div>
                  {{ item.name }}
                </div>
                <div class="text " style="display: flex">
                  <div class="txt">
                    <div class="txt-item">
                      <div class="label">所属分类</div>
                      <div class="value active">{{ getCateName(item.categoryId) }}</div>
                    </div>
                    <div class="txt-item">
                      <div class="label">产品类型</div>
                      <div class="value">{{ getNodeTypeName(item.nodeType) }}</div>
                    </div>
                    <div class="txt-item">
                      <div class="label">设备定位</div>
                      <div class="value">
                        {{ item.openLocate == 1 ? (item.locateUpdateType == 1 ? '手动' : '设备上报') : '关闭' }}
                      </div>
                    </div>
                  </div>
                  <div class="img">
                    <img :src="item.imgUrl || defaultImg" alt=""/>
                  </div>
                </div>
                <div class="btn-group">
                  <el-button class="cu-btn" type="primary" icon="EditPen" plain @click="handleUpdate(item)">编辑
                  </el-button>
                  <el-button class="cu-btn" type="warning" icon="View" plain @click="handleDetail(item)">详情</el-button>
                  <el-button class="cu-btn" type="success" icon="ScaleToOriginal" plain @click="openObjectModel(item)">物模型</el-button>
                  <el-divider direction="vertical"/>
                  <el-button type="danger" icon="Delete" @click="handleDelete(item)" plain/>
                </div>
              </div>
            </el-col>
          </el-row>
        </template>

      </el-card>
    </el-col>
  </div>

  <!-- 添加设备产品对话框 -->
  <el-dialog :title="title" v-model="open" width="600px" append-to-body>
    <el-form :model="form" :rules="rules" ref="productRef" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品Key" prop="productKey">
            <el-input v-model="form.productKey" placeholder="请输入产品Key" maxlength="11"
                      :disabled="form.id!=undefined"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入产品名称" maxlength="50"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="存活时长" prop="keepAliveTime">
            <el-input v-model="form.keepAliveTime" placeholder="请输设备存活时长" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品类" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择产品品类" size="default">
              <el-option v-for="item in categoryList" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品类型" prop="nodeType">
            <el-select v-model="form.nodeType" placeholder="请选择产品类型" size="default">
              <el-option v-for="item in nodeTypeOptions" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="传输协议" prop="transMode">
            <el-select v-model="form.transMode" placeholder="请选择传输协议" size="default">
              <el-option v-for="item in equip_gateway_protocol" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备定位" prop="openLocate">
            <el-radio-group v-model="form.openLocate">
              <el-radio
                  v-for="dict in openLocateOptions"
                  :key="dict.value"
                  :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="form.openLocate==1">
          <el-form-item label="上报方式" prop="locateUpdateType">
            <el-radio-group v-model="form.locateUpdateType">
              <el-radio
                  v-for="dict in locateUpdateTypeOptions"
                  :key="dict.value"
                  :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备图片" prop="img">
            <file-upload
                v-model="form.img"
                :model-value="form.img"
                :is-show-tip="true"
                :file-size="500"
                :limit="1"
                :file-type="[]"
            >
            </file-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <object-model ref="objectModelRef"/>

</template>

<script setup>
import defaultImg from '@/assets/images/pic_device.png'
import {addProduct, delProduct, listProduct, updateProduct} from "@/api/equip/product";
import {selectList} from "@/api/equip/categroy";
import FileUpload from "@/components/FileUpload";
import objectModel from './objectModel'
import {validatePositiveInteger, validateStringAndNumber} from "@/utils/vaild-rule";
import ObjectModel from "@/views/equipment/product/objectModel";

const {proxy} = getCurrentInstance();
const {equip_gateway_protocol} = proxy.useDict("equip_gateway_protocol");
const layoutType = ref('table')
const showSearch = ref(true);
const loading = ref(false)
const title = ref(undefined)
const open = ref(false)
const total = ref(0);
const dialogType = ref(undefined)
const productList = ref([])
const categoryList = ref([])
const data = reactive({
  form: {},
  queryParams: {},
  rules: {
    productKey: [{required: true, message: "品类id不能为空", trigger: "blur"}, {
      validator: validateStringAndNumber,
      trigger: "blur"
    }],
    name: [{required: true, message: "产品名称不能为空", trigger: "blur"}],
    keepAliveTime: [{required: true, message: "品类id不能为空", trigger: "blur"}, {
      validator: validatePositiveInteger,
      trigger: "blur"
    }],
    categoryId: [{required: true, message: "品类名称不能为空", trigger: "blur"}],
  }
})
const {queryParams, form, rules} = toRefs(data);


/** 搜索按钮操作 */
function handleQuery() {
  // getList();
};

function reset() {
  form.value.openLocate = 0
  form.value.locateUpdateType = 1
  form.value.keepAliveTime = 60
}

function handleAdd() {
  reset()
  title.value = '新增设备产品'
  dialogType.value = 1
  open.value = true
}


function handleUpdate(product) {
  form.value = {...product}
  title.value = '修改设备产品'
  dialogType.value = 2
  open.value = true
}

function computedTransMode(mode) {
  return equip_gateway_protocol.value.find((f) => f.value == mode)?.label || ''
}


function computedOpenLocate(openLocate, locateUpdateType) {
  if (openLocate === 1) {
    return locateUpdateTypeOptions.find((f) => f.value == locateUpdateType)?.label || ''
  } else {
    return '关闭'
  }
}


const locateUpdateTypeOptions = [
  {
    value: 1,
    label: "手动更新"
  },
  {
    value: 2,
    label: "设备上传"
  }
]
const openLocateOptions = [
  {
    value: 1,
    label: "开启"
  },
  {
    value: 0,
    label: "关闭"
  }
]

const nodeTypeOptions = [
  {
    value: 0,
    label: '网关设备',
  },
  {
    value: 1,
    label: '网关子设备',
  },
  {
    value: 2,
    label: '直连设备',
  },
]


/**
 * 查询品类
 */
function getCateoryList() {
  selectList().then(res => {
    categoryList.value = res.data
  })
}

/** 查询产品列表 */
function getList() {
  loading.value = true;
  listProduct(proxy.addDateRange(queryParams.value)).then(res => {
    loading.value = false;
    productList.value = res.rows
    productList.value.forEach(item => {
      if (item.img) {
        item.imgUrl = import.meta.env.VITE_APP_BASE_API + item.img
      }
    });
    total.value = res.total;
  })
};

const objectModelRef=ref(null)
function openObjectModel(row){
  objectModelRef.value.getInfo(row.id)
}

// 获取分类名称
function getCateName(id) {
  return categoryList.value.find((cate) => cate.value === id)?.label || ''
}

// 获取产品类型
function getNodeTypeName(type) {
  return nodeTypeOptions.find((f) => f.value === type)?.label || ''
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (dialogType.value == 1) {
        addProduct(form.value).then(res => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        })
      } else {
        updateProduct(form.value).then(res => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        })
      }
    }
  });
};


function handleDelete(product) {
  proxy.$modal.confirm('是否确认删除产品Key为"' + product.productKey + '"的数据项？').then(function () {
    return delProduct(product.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
getCateoryList()
getList()
</script>

<style lang="scss" scoped>
.rightToolbar {
  display: flex;
  align-items: center;
  padding-right: 10px;
}

.card-list {
  .card-item {
    border: 1px solid #d8dee5;
    border-radius: 3px;
    margin-right: 16px;
    margin-bottom: 16px;
    flex: 0 0 calc(25% - 12px);
    min-width: calc(25% - 12px);

    &:nth-child(4n) {
      margin-right: 0;
    }

    .text-box {
      padding: 16px;

      .title {
        font-size: 16px;
        font-weight: 600;
        align-items: center;
        margin-bottom: 12px;

        .icon {
          margin-right: 10px;
          display: flex;
          align-items: center;
        }
      }

      .text {
        align-items: center;
        font-size: 14px;

        .txt {
          flex: 1;

          .txt-item {
            margin-bottom: 10px;

            &:last-child {
              margin-bottom: 0;
            }
          }

          .label {
            display: inline-block;
            margin-right: 10px;
            color: #717c8e;
          }

          .value {
            display: inline-block;
            color: #0b1d30;

            &.active {
              color: #0070ff;
            }
          }
        }

        .img {
          width: 100px;
          height: 100px;

          img {
            width: 100%;
            height: auto;
          }
        }
      }
    }

    .btn-group {
      padding: 12px 16px;
      border-top: 1px solid #dcdfe1;

      .cu-btn {
        width: calc((100% - 73px) / 3);
      }

      .el-button {
        padding: 8px;
      }
    }
  }
}

@media screen and (max-width: 1560px) {
  .card-list .card-item .btn-group {
    padding: 12px;

    .el-button {
      font-size: 12px;
    }

    .cu-btn {
      width: calc((100% - 59px) / 3);
    }

    .el-button + .el-button {
      margin-left: 6px;
    }
  }
}

@media screen and (max-width: 1400px) {
  .card-list .card-item {
    width: calc(100% / 3 - 8px);
    flex: 0 0 calc(100% / 3 - 8px);
    margin-right: 12px;

    &:nth-child(4n) {
      margin-right: 12px;
    }

    &:nth-child(3n) {
      margin-right: 0;
    }
  }
}
</style>
